import { checkPagePermission, PERMISSIONS, getAllPermissions, getPermissionName } from '../../utils/permission.js'

Page({
  data: {
    hasPermission: false,
    loading: true,
    currentTab: 'users',
    users: [],
    filteredUsers: [], // 筛选后的用户列表
    roles: [],
    showEditDialog: false,
    showAddRoleDialog: false,
    editingUser: null,
    editingRoleId: null,
    selectedRole: null,
    selectedRoleIndex: -1,
    roleOptions: [],
    // 搜索和筛选
    searchKeyword: '',
    selectedRoleFilter: 0,
    selectedStatusFilter: 0,
    roleFilterOptions: [
      { key: 'all', name: '全部角色' },
      { key: 'super_admin', name: '超级管理员' },
      { key: 'admin', name: '管理员' },
      { key: 'manager', name: '业务经理' },
      { key: 'auditor', name: '审核员' },
      { key: 'service_admin', name: '服务管理员' },
      { key: 'user', name: '普通用户' },
      { key: 'custom', name: '自定义权限' }
    ],
    statusFilterOptions: [
      { key: 'all', name: '全部状态' },
      { key: 'has_permission', name: '已分配权限' },
      { key: 'no_permission', name: '未分配权限' }
    ],
    newRole: {
      roleName: '',
      description: '',
      permissions: []
    },
    allPermissions: getAllPermissions().map(p => ({
      ...p,
      checked: false,
      roleChecked: false
    }))
  },

  onLoad() {
    wx.setNavigationBarTitle({
      title: '用户权限管理'
    })

    this.checkPermission()
  },

  // 检查权限
  async checkPermission() {
    try {
      console.log('🔍 用户权限管理页面检查权限')

      // 获取用户完整权限信息
      const permissionResult = await wx.cloud.callFunction({
        name: 'checkUserPermission',
        data: { permission: 'basic' }
      })

      let hasPermission = false

      if (permissionResult.result && permissionResult.result.success) {
        const data = permissionResult.result.data
        let rawPermissions = data.permissions || ['basic']
        const userRole = data.role || 'user'

        // 处理权限数据类型问题
        let userPermissions = ['basic']
        if (typeof rawPermissions === 'string') {
          try {
            userPermissions = JSON.parse(rawPermissions)
            console.log('🔧 权限管理页面：权限数据从字符串转换为数组:', userPermissions)
          } catch (error) {
            console.warn('⚠️ 权限字符串解析失败:', error)
            userPermissions = ['basic']
          }
        } else if (Array.isArray(rawPermissions)) {
          userPermissions = rawPermissions
        }

        // 检查是否有管理员权限（包括角色检查）
        hasPermission = userPermissions.includes('admin') ||
                       userPermissions.includes('super_admin') ||
                       userRole === 'admin' ||
                       userRole === 'super_admin'

        console.log('📋 权限管理页面权限检查:', {
          permissions: userPermissions,
          role: userRole,
          hasAdmin: userPermissions.includes('admin'),
          hasSuperAdmin: userPermissions.includes('super_admin'),
          isAdminRole: userRole === 'admin' || userRole === 'super_admin',
          finalPermission: hasPermission
        })
      }

      this.setData({
        hasPermission: hasPermission,
        loading: false
      })

      if (hasPermission) {
        console.log('✅ 权限检查通过，加载数据')
        this.loadData()
      } else {
        console.log('❌ 权限检查失败')
        wx.showToast({
          title: '权限不足',
          icon: 'none'
        })
      }

    } catch (error) {
      console.error('❌ 权限检查异常:', error)
      this.setData({
        hasPermission: false,
        loading: false
      })
      wx.showToast({
        title: '权限检查失败',
        icon: 'none'
      })
    }
  },

  // 加载数据
  async loadData() {
    this.setData({ loading: true })
    
    try {
      await Promise.all([
        this.loadUsers(),
        this.loadRoles()
      ])
    } catch (error) {
      console.error('❌ 加载数据失败:', error)
      wx.showToast({
        title: '加载数据失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载用户列表
  async loadUsers() {
    try {
      // 获取有权限记录的用户
      const permissionUsersResult = await wx.cloud.callFunction({
        name: 'manageUserPermissions',
        data: {
          action: 'getAllUsers'
        }
      })

      // 获取所有注册用户
      const allUsersResult = await wx.cloud.callFunction({
        name: 'manageUserPermissions',
        data: {
          action: 'getAllRegisteredUsers'
        }
      })

      let users = []

      if (permissionUsersResult.result && permissionUsersResult.result.success) {
        users = permissionUsersResult.result.data
      }

      // 如果有注册用户数据，合并显示
      if (allUsersResult.result && allUsersResult.result.success) {
        const registeredUsers = allUsersResult.result.data

        // 合并用户数据，避免重复
        registeredUsers.forEach(regUser => {
          const existingUser = users.find(u => u.openid === regUser.openid)
          if (!existingUser) {
            // 添加没有权限记录的用户，设置默认权限
            users.push({
              openid: regUser.openid,
              permissions: ['basic'],
              role: 'user',
              roleName: '普通用户',
              userInfo: {
                nickName: regUser.nickName || '未知用户',
                avatarUrl: regUser.avatarUrl || '',
                lastLoginTime: regUser.lastLoginTime || null,
                loginCount: regUser.loginCount || 0
              },
              updateTime: regUser.createTime || new Date(),
              hasPermissionRecord: false // 标记是否有权限记录
            })
          } else {
            // 更新现有用户的信息
            existingUser.hasPermissionRecord = true
          }
        })
      }

      // 按更新时间排序
      users.sort((a, b) => new Date(b.updateTime) - new Date(a.updateTime))

      this.setData({
        users: users
      })

      // 应用筛选
      this.applyFilters()

      console.log('✅ 用户列表加载成功:', users.length, '个用户')

    } catch (error) {
      console.error('❌ 加载用户列表失败:', error)
      throw error
    }
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
    this.applyFilters()
  },

  // 角色筛选变化
  onRoleFilterChange(e) {
    this.setData({
      selectedRoleFilter: e.detail.value
    })
    this.applyFilters()
  },

  // 状态筛选变化
  onStatusFilterChange(e) {
    this.setData({
      selectedStatusFilter: e.detail.value
    })
    this.applyFilters()
  },

  // 应用筛选
  applyFilters() {
    let filteredUsers = [...this.data.users]

    // 搜索筛选
    if (this.data.searchKeyword.trim()) {
      const keyword = this.data.searchKeyword.trim().toLowerCase()
      filteredUsers = filteredUsers.filter(user =>
        user.userInfo.nickName.toLowerCase().includes(keyword) ||
        user.openid.toLowerCase().includes(keyword)
      )
    }

    // 角色筛选
    const roleFilter = this.data.roleFilterOptions[this.data.selectedRoleFilter]
    if (roleFilter.key !== 'all') {
      filteredUsers = filteredUsers.filter(user => user.role === roleFilter.key)
    }

    // 状态筛选
    const statusFilter = this.data.statusFilterOptions[this.data.selectedStatusFilter]
    if (statusFilter.key === 'has_permission') {
      filteredUsers = filteredUsers.filter(user => user.hasPermissionRecord !== false)
    } else if (statusFilter.key === 'no_permission') {
      filteredUsers = filteredUsers.filter(user => user.hasPermissionRecord === false)
    }

    this.setData({
      filteredUsers: filteredUsers
    })

    console.log('🔍 筛选结果:', filteredUsers.length, '个用户')
  },

  // 清除筛选
  clearFilters() {
    this.setData({
      searchKeyword: '',
      selectedRoleFilter: 0,
      selectedStatusFilter: 0
    })
    this.applyFilters()
  },

  // 加载角色列表
  async loadRoles() {
    try {
      const result = await wx.cloud.callFunction({
        name: 'manageUserPermissions',
        data: {
          action: 'getAllRoles'
        }
      })

      if (result.result && result.result.success) {
        const roles = result.result.data
        this.setData({
          roles: roles,
          roleOptions: [
            { roleName: '自定义权限', roleKey: 'custom' },
            ...roles
          ]
        })
        console.log('✅ 角色列表加载成功:', roles.length)
      } else {
        throw new Error(result.result?.error || '加载角色失败')
      }

    } catch (error) {
      console.error('❌ 加载角色列表失败:', error)
      throw error
    }
  },

  // 切换选项卡
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ currentTab: tab })
  },

  // 编辑用户权限
  editUserPermissions(e) {
    const openid = e.currentTarget.dataset.openid
    const user = this.data.users.find(u => u.openid === openid)

    if (!user) return

    // 设置权限复选框状态
    const allPermissions = this.data.allPermissions.map(permission => ({
      ...permission,
      checked: user.permissions.includes(permission.key)
    }))

    // 查找匹配的角色
    let selectedRole = null
    let selectedRoleIndex = -1

    if (user.role && user.role !== 'custom') {
      selectedRole = this.data.roles.find(role => role.roleKey === user.role)
      if (selectedRole) {
        selectedRoleIndex = this.data.roleOptions.findIndex(option => option._id === selectedRole._id)
      }
    }

    // 如果是新用户（没有权限记录），默认选择普通用户角色
    if (!user.hasPermissionRecord) {
      const userRole = this.data.roles.find(role => role.roleKey === 'user')
      if (userRole) {
        selectedRole = userRole
        selectedRoleIndex = this.data.roleOptions.findIndex(option => option._id === userRole._id)

        // 更新权限复选框为用户角色的权限
        const updatedPermissions = allPermissions.map(permission => ({
          ...permission,
          checked: userRole.permissions.includes(permission.key)
        }))

        this.setData({
          allPermissions: updatedPermissions
        })
      }
    }

    this.setData({
      showEditDialog: true,
      editingUser: user,
      allPermissions: allPermissions,
      selectedRole: selectedRole,
      selectedRoleIndex: selectedRoleIndex
    })
  },

  // 查看用户详情
  viewUserDetails(e) {
    const openid = e.currentTarget.dataset.openid
    const user = this.data.users.find(u => u.openid === openid)
    
    if (!user) return

    const permissionNames = user.permissions.map(p => this.getPermissionName(p)).join('、')
    
    wx.showModal({
      title: '用户详情',
      content: `用户: ${user.userInfo.nickName}\nID: ${user.openid}\n角色: ${user.roleName}\n权限: ${permissionNames}\n登录次数: ${user.userInfo.loginCount}`,
      showCancel: false
    })
  },

  // 角色选择变化
  onRoleChange(e) {
    const index = e.detail.value
    const selectedRole = this.data.roleOptions[index]
    
    if (selectedRole.roleKey === 'custom') {
      // 自定义权限，不改变当前权限设置
      this.setData({
        selectedRole: null,
        selectedRoleIndex: index
      })
    } else {
      // 预设角色，更新权限复选框
      const allPermissions = this.data.allPermissions.map(permission => ({
        ...permission,
        checked: selectedRole.permissions ? selectedRole.permissions.includes(permission.key) : false
      }))
      
      this.setData({
        selectedRole: selectedRole,
        selectedRoleIndex: index,
        allPermissions: allPermissions
      })
    }
  },

  // 权限复选框变化
  onPermissionChange(e) {
    const permission = e.currentTarget.dataset.permission
    const checked = e.detail.value.length > 0
    
    const allPermissions = this.data.allPermissions.map(p => 
      p.key === permission ? { ...p, checked: checked } : p
    )
    
    this.setData({ 
      allPermissions: allPermissions,
      selectedRole: null, // 自定义权限时清除角色选择
      selectedRoleIndex: 0 // 设为自定义权限
    })
  },

  // 保存用户权限
  async saveUserPermissions() {
    if (!this.data.editingUser) return

    const isNewUser = !this.data.editingUser.hasPermissionRecord

    wx.showLoading({
      title: isNewUser ? '分配权限中...' : '保存中...'
    })

    try {
      const selectedPermissions = this.data.allPermissions
        .filter(p => p.checked)
        .map(p => p.key)

      // 验证权限选择
      if (selectedPermissions.length === 0) {
        wx.showToast({
          title: '请至少选择一个权限',
          icon: 'none'
        })
        return
      }

      let result

      if (this.data.selectedRole && this.data.selectedRole._id) {
        // 设置角色
        result = await wx.cloud.callFunction({
          name: 'manageUserPermissions',
          data: {
            action: 'setUserRole',
            targetOpenid: this.data.editingUser.openid,
            roleId: this.data.selectedRole._id,
            userInfo: this.data.editingUser.userInfo // 传递用户信息用于记录
          }
        })
      } else {
        // 设置自定义权限
        result = await wx.cloud.callFunction({
          name: 'manageUserPermissions',
          data: {
            action: 'setUserPermissions',
            targetOpenid: this.data.editingUser.openid,
            permissions: selectedPermissions,
            userInfo: this.data.editingUser.userInfo // 传递用户信息用于记录
          }
        })
      }

      if (result.result && result.result.success) {
        wx.showToast({
          title: isNewUser ? '权限分配成功' : '保存成功',
          icon: 'success'
        })

        // 记录操作日志
        console.log(`✅ ${isNewUser ? '新用户权限分配' : '用户权限更新'}成功:`, {
          openid: this.data.editingUser.openid,
          nickName: this.data.editingUser.userInfo.nickName,
          permissions: selectedPermissions,
          role: this.data.selectedRole?.roleName || '自定义权限'
        })

        this.hideEditDialog()
        this.loadUsers() // 重新加载用户列表
      } else {
        throw new Error(result.result?.error || '保存失败')
      }

    } catch (error) {
      console.error('❌ 保存用户权限失败:', error)
      wx.showModal({
        title: '保存失败',
        content: error.message,
        showCancel: false
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 隐藏编辑弹窗
  hideEditDialog() {
    this.setData({
      showEditDialog: false,
      editingUser: null,
      selectedRole: null,
      selectedRoleIndex: -1
    })
  },

  // 显示添加角色弹窗
  showAddRoleDialog() {
    const allPermissions = this.data.allPermissions.map(permission => ({
      ...permission,
      roleChecked: false
    }))

    this.setData({
      showAddRoleDialog: true,
      editingRoleId: null,
      newRole: {
        roleName: '',
        description: '',
        permissions: []
      },
      allPermissions: allPermissions
    })
  },

  // 隐藏添加角色弹窗
  hideAddRoleDialog() {
    this.setData({
      showAddRoleDialog: false,
      editingRoleId: null,
      newRole: {
        roleName: '',
        description: '',
        permissions: []
      }
    })
  },

  // 角色名称输入
  onRoleNameInput(e) {
    this.setData({
      'newRole.roleName': e.detail.value
    })
  },

  // 角色描述输入
  onRoleDescInput(e) {
    this.setData({
      'newRole.description': e.detail.value
    })
  },

  // 角色权限复选框变化
  onRolePermissionChange(e) {
    const permission = e.currentTarget.dataset.permission
    const checked = e.detail.value.length > 0
    
    const allPermissions = this.data.allPermissions.map(p => 
      p.key === permission ? { ...p, roleChecked: checked } : p
    )
    
    this.setData({ allPermissions: allPermissions })
  },

  // 保存角色
  async saveRole() {
    const { roleName, description } = this.data.newRole
    
    if (!roleName.trim()) {
      wx.showToast({
        title: '请输入角色名称',
        icon: 'none'
      })
      return
    }

    const selectedPermissions = this.data.allPermissions
      .filter(p => p.roleChecked)
      .map(p => p.key)

    if (selectedPermissions.length === 0) {
      wx.showToast({
        title: '请选择至少一个权限',
        icon: 'none'
      })
      return
    }

    wx.showLoading({ title: '保存中...' })

    try {
      const action = this.data.editingRoleId ? 'updateRole' : 'createRole'
      const data = {
        action: action,
        roleName: roleName.trim(),
        rolePermissions: selectedPermissions,
        roleDescription: description.trim()
      }

      if (this.data.editingRoleId) {
        data.roleId = this.data.editingRoleId
      }

      const result = await wx.cloud.callFunction({
        name: 'manageUserPermissions',
        data: data
      })

      if (result.result && result.result.success) {
        wx.showToast({
          title: this.data.editingRoleId ? '更新成功' : '创建成功',
          icon: 'success'
        })
        this.hideAddRoleDialog()
        this.loadRoles() // 重新加载角色列表
      } else {
        throw new Error(result.result?.error || '保存失败')
      }

    } catch (error) {
      console.error('❌ 保存角色失败:', error)
      wx.showModal({
        title: '保存失败',
        content: error.message,
        showCancel: false
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 编辑角色
  editRole(e) {
    const roleId = e.currentTarget.dataset.id
    const role = this.data.roles.find(r => r._id === roleId)
    
    if (!role) return

    const allPermissions = this.data.allPermissions.map(permission => ({
      ...permission,
      roleChecked: role.permissions.includes(permission.key)
    }))

    this.setData({
      showAddRoleDialog: true,
      editingRoleId: roleId,
      newRole: {
        roleName: role.roleName,
        description: role.description,
        permissions: role.permissions
      },
      allPermissions: allPermissions
    })
  },

  // 删除角色
  deleteRole(e) {
    const roleId = e.currentTarget.dataset.id
    const role = this.data.roles.find(r => r._id === roleId)
    
    if (!role) return

    wx.showModal({
      title: '确认删除',
      content: `确定要删除角色"${role.roleName}"吗？此操作不可撤销。`,
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' })

          try {
            const result = await wx.cloud.callFunction({
              name: 'manageUserPermissions',
              data: {
                action: 'deleteRole',
                roleId: roleId
              }
            })

            if (result.result && result.result.success) {
              wx.showToast({
                title: '删除成功',
                icon: 'success'
              })
              this.loadRoles() // 重新加载角色列表
            } else {
              throw new Error(result.result?.error || '删除失败')
            }

          } catch (error) {
            console.error('❌ 删除角色失败:', error)
            wx.showModal({
              title: '删除失败',
              content: error.message,
              showCancel: false
            })
          } finally {
            wx.hideLoading()
          }
        }
      }
    })
  },

  // 刷新数据
  refreshData() {
    this.loadData()
  },

  // 返回
  goBack() {
    wx.navigateBack()
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  },

  // 获取权限名称
  getPermissionName(permissionKey) {
    return getPermissionName(permissionKey)
  }
})
